package com.mall.activiti.config;

import com.central.common.utils.GlobalUserContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.entity.Users;
import com.mall.security.TokenManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CustInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StringUtils.isNoneBlank(token)){
           String userName = TokenManager.getUserInfoFromToken(token);
            //从redis获取用户信息
            String userInfo = (String)redisTemplate.boundValueOps(userName).get();
            try {
                Users user = objectMapper.readValue(userInfo, Users.class);
                GlobalUserContext.setUser(user);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}